/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Test;

import MNetSockets.DataChanel.DataClient;
import MNetSockets.DataChanel.IUDPDataReader;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author wcss
 */
public class UDPHealthTest extends javax.swing.JFrame implements IUDPDataReader {

    public DataClient dc = new DataClient(63891);
    private long msgIndex = 0;
    private long sendCounts = 0;
    private long receiveCounts = 0;
    private long sendTotals = 0;
    private String tempData = "";

    public long getMsgIndex() {
        msgIndex++;
        return msgIndex;
    }

    public void sendUDPMsg(String ip, String content) {
        try {
            dc.send(new InetSocketAddress(ip, 63891), content + "-MsgIndex:" + tempData + "-" +getMsgIndex());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Creates new form UDPHealthTest
     */
    public UDPHealthTest() {
        initComponents();
        dc.receiveEvent = this;
        this.jsrSendCount.setValue(3000000);
        try {
            dc.start();
        } catch (Exception ex) {
            Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        StringBuilder sb = new StringBuilder();
        for(int kk = 0;kk< 800;kk++)
        {
            sb.append("8");
        }
        this.tempData = sb.toString();
        sb = null;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jsrSendCount = new javax.swing.JSpinner();
        lblSendCount = new javax.swing.JLabel();
        lblReceiveCount = new javax.swing.JLabel();
        btnStartTest = new javax.swing.JButton();
        lblLostCount = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("发送消息数：");

        lblSendCount.setText("jLabel2");

        lblReceiveCount.setText("jLabel2");

        btnStartTest.setText("开始测试");
        btnStartTest.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStartTestActionPerformed(evt);
            }
        });

        lblLostCount.setText("jLabel2");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnStartTest)
                .addGap(206, 206, 206))
            .addGroup(layout.createSequentialGroup()
                .addGap(158, 158, 158)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(4, 4, 4)
                        .addComponent(jsrSendCount, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(lblSendCount, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblReceiveCount, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblLostCount, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(430, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(61, 61, 61)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jsrSendCount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(lblSendCount, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblReceiveCount, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblLostCount)
                .addGap(60, 60, 60)
                .addComponent(btnStartTest)
                .addContainerGap(159, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnStartTestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartTestActionPerformed
        // TODO add your handling code here:
        sendCounts = 1;
        receiveCounts = 0;
        sendTotals = (long) Integer.parseInt(this.jsrSendCount.getValue().toString());
//        this.sendUDPMsg("108.171.204.250", "remote");

        Thread tt = new Thread(new Runnable() 
        {
            public void run() 
            {
                for (int k = 0; k < sendTotals; k++) {
                    if (sendCounts <= sendTotals) {
                        sendUDPMsg("108.171.204.250", "remote");
                        sendCounts++;
                        lblSendCount.setText("已发送：" + sendCounts + "/" + sendTotals);
                    }

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(UDPHealthTest.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        });
        tt.setDaemon(true);
        tt.start();
    }//GEN-LAST:event_btnStartTestActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(UDPHealthTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(UDPHealthTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(UDPHealthTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(UDPHealthTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new UDPHealthTest().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnStartTest;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JSpinner jsrSendCount;
    private javax.swing.JLabel lblLostCount;
    private javax.swing.JLabel lblReceiveCount;
    private javax.swing.JLabel lblSendCount;
    // End of variables declaration//GEN-END:variables

    @Override
    public void dataRead(Object o, SocketAddress sa, Object o1) {
        String curIP = ((InetSocketAddress) sa).getAddress().getHostAddress();
        receiveCounts++;
        this.lblReceiveCount.setText("已接收：" + receiveCounts + "/" + sendTotals);
        this.lblLostCount.setText("已丢失：" + (sendCounts - receiveCounts) + "丢包率：" +  (int)((((double)(sendCounts - receiveCounts)) / ((double)sendCounts)) * 100) + "%");
    }
}
